package com.leenmvc.core.security.service.core;

import com.leenmvc.core.annotation.TransactionMulti;
import com.leenmvc.core.base.BaseService;
import com.leenmvc.core.exception.BusinessException;
import com.leenmvc.core.security.dao.core.SysDictDao;
import com.leenmvc.core.security.entity.core.SysDict;
import com.leenmvc.core.utils.dictionary.Dict;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class SysDictService extends BaseService<SysDict> {

    @Autowired
    private SysDictDao sysDictDao;

    @TransactionMulti
    public void updateDict(Map<String,Object> params) {
         if(update(params) == 0) {
             throw new BusinessException("字典表更新失败！请检查你的参数！");
         }
    }

    /**
     * 重写更新字典表记录的方法
     * @param t
     * @param <T>
     * @return
     */
    @TransactionMulti
    public <T> boolean update(T t) {
        SysDict sysDict = (SysDict)t;
        if(!super.update(t)) {
            throw new BusinessException("UPDATE_FAIL", SysDict.class);
        };
        Dict.updateValue(sysDict.getDictType(), sysDict.getDictName(), sysDict.getDictValue());
        return true;
    }

    /**
     * 重写保存字典表记录的方法
     * @param t
     * @param <T>
     * @return
     */
    @TransactionMulti
    public <T> boolean insert(T t) {
        SysDict sysDict = (SysDict)t;
        if(!super.insert(t)) {
            throw new BusinessException("INSERT_FAIL", SysDict.class);
        };
        Dict.insertValue(sysDict.getDictType(), sysDict.getDictName(), sysDict.getDictValue());
        return true;
    }

    @Override
    public int deleteByIds(Object[] ids) {
        Long id = (Long) ids[0];
        List<SysDict> dictList = dictPid(id);
        int size = dictList.size();
        if (size>0) {
            throw new BusinessException("该类型下有数据，请检查！");
        }
        if (dictId(id)==null) {
            throw new BusinessException("字典表无此条数据，请检查！");
        }
        return sysDictDao.deleteByIds(ids);
    }
}
